package cn.sycoder.service.impl;

import cn.sycoder.entity.RoleMenu;
import cn.sycoder.mapper.RoleMenuMapper;
import cn.sycoder.service.IRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杨润发
 * @since 2024-10-22
 */
@Service
@Transactional
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    public boolean saveRoleRights(Long roleId, List<Long> menuIds) {
        try {
            // 在保存之前先删除与其相关联的菜单
            roleMenuMapper.deleteByRoleId(roleId);

            List<RoleMenu> roleMenus = new ArrayList<>();
            for (Long menuId : menuIds) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menuId);
                roleMenus.add(roleMenu);
            }
            return saveBatch(roleMenus);
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存角色菜单权限时出错", e);
            return false;
        }
    }
}
